package com.zmj.sy.mom.srv.aps.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.http.HttpUtil;
import com.zmj.sy.mom.srv.aps.bean.entity.order.OrderPart;
import com.zmj.sy.mom.srv.aps.bean.vo.file.FileUploadResVo;
import com.zmj.sy.mom.srv.aps.mapper.OrderPartMapper;
import com.zmj.sy.mom.srv.aps.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RequiredArgsConstructor
@Api(tags = "文件")
@RestController
@RequestMapping("/file")
public class FileController {

    private final RestTemplate restTemplate;
    private final OrderPartMapper orderPartMapper;
    @Value("${project.ftp.url}")
    // FTP地址
    private String ftpUrl;

    @Value("${project.ftp.port}")
    // FTP端口
    private Integer ftpPort;

    @Value("${project.ftp.user}")
    // FTP账号
    private String ftpUser;

    @Value("${project.ftp.password}")
    // FTP密码
    private String ftpPassword;

    @Value("${project.ftp.charset-name}")
    // FTP编码
    private String ftpCharsetName;

    @ApiOperation("钢板PDF转PNG")
    @GetMapping("/NestFramePDFFile/{filename}")
    public ResponseEntity<byte[]> pdfToPng(@PathVariable("filename") String filename1) throws IOException {

        byte[] bytes = HttpUtil.downloadBytes(WorkshopProp.NESTING_DRAWING_CTX + "Downloads/NestFramePDFFile/" + filename1);
        PDDocument document = PDDocument.load(bytes);
        PDFRenderer renderer = new PDFRenderer(document);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int pageIndex = 0; pageIndex < document.getNumberOfPages(); pageIndex++) {
            BufferedImage image = renderer.renderImageWithDPI(pageIndex, 300); // 设置DPI
            ImageIO.write(image, "PNG", baos);
        }

        // 下载
        String filename = org.springframework.util.StringUtils.getFilename(filename1) + ".png";
        String fileName = new String(filename.getBytes("utf-8"), "iso-8859-1"); //解决中文乱码问题
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);// aatachment  附件
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);

    }


    @ControllerAspectIgnore
    @ApiOperation("图纸下载")
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(String path) throws IOException {

        if (path.contains("home")) {
            File file = new File(path);
            if (!file.exists()) {
                throw SyExceptionUtils.e("文件不存在");
            }
            byte[] bytes = FileUtils.readFileToByteArray(file);

            // 下载
            String filename = org.springframework.util.StringUtils.getFilename(path);
            String downFileName = new String(filename.getBytes("utf-8"), "iso-8859-1"); //解决中文乱码问题
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", downFileName);// aatachment  附件
            headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

        } else {

            File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".dxf");

//        try (Ftp ftp = new Ftp("172.31.3.31", 21, "PLM", "L2ftp", Charset.forName("GBK"))) {
            // 旧 Ftp 地址，账号，密码

            // 新 Ftp 地址，账号，密码
            try (Ftp ftp = new Ftp(ftpUrl, ftpPort, ftpUser, ftpPassword, Charset.forName(ftpCharsetName))) {
                ftp.download(path, tempFile);
            }
            byte[] bytes = FileUtils.readFileToByteArray(tempFile);
            tempFile.deleteOnExit();

            // 下载
            String filename = org.springframework.util.StringUtils.getFilename(path);
            String fileName = new String(filename.getBytes("utf-8"), "iso-8859-1"); //解决中文乱码问题
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", fileName);// aatachment  附件
            headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
        }

    }
//    Downloads/NestFramePDFFile/3240520A0001.pdf


    @ControllerAspectIgnore
    @ApiOperation("FTP文件下载")
    @GetMapping("/ftp/download/**")
    public ResponseEntity<byte[]> ftpDownload() throws IOException {

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HttpServletRequest request = ServletUtils.getRequest();
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String matchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        String filename1 = "/" + antPathMatcher.extractPathWithinPattern(matchPattern, path);

        String prefix = FileNameUtil.getPrefix(filename1);
        String suffix = FileNameUtil.getSuffix(filename1);

        File tempFile = File.createTempFile(prefix, "." + suffix);
        try (Ftp ftp = new Ftp(ftpUrl, ftpPort, ftpUser, ftpPassword, Charset.forName(ftpCharsetName))) {
            ftp.download(filename1, tempFile);
        }
        byte[] bytes = FileUtils.readFileToByteArray(tempFile);
        tempFile.deleteOnExit();

        // 下载
        String filename = FileNameUtil.getName(filename1);
        String fileName = new String(filename.getBytes("utf-8"), "iso-8859-1"); //解决中文乱码问题
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);// aatachment  附件
        if (suffix.equalsIgnoreCase("pdf")) {
            headers.setContentType(MediaType.APPLICATION_PDF);
        } else {
            headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        }
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @ControllerAspectIgnore
    @ApiOperation("文件下载")
    @GetMapping("/down")
    public ResponseEntity<byte[]> down(String path, String filename) throws IOException {

        byte[] bytes = null;

        if (path.startsWith("http")) {
            try {
                bytes = this.getFile(path);
            } catch (FileNotFoundException e) {
                String str = "http://172.31.3.55:8290/fileManage/convertImages";
                Map<String, Object> params = new HashMap<>();
                params.put("dateDiff", 0);
                params.put("fileType", "part");
                if(filename.indexOf(".") > 0){
                    params.put("objectNo", filename.substring(0, filename.indexOf(".")));
                } else {
                    params.put("objectNo", filename);
                }

                HttpUtil.post(str, JsonUtils.toJsonString(params));

                bytes = this.getFile(path);

            } catch (Exception e) {
                throw SyExceptionUtils.e("文件下载失败");
            }
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw SyExceptionUtils.e("文件不存在");
            }
            bytes = FileUtils.readFileToByteArray(file);
        }

        // 下载
        if (!StringUtils.hasText(filename)) {
            filename = org.springframework.util.StringUtils.getFilename(path);
        }
        String downFileName = new String(filename.getBytes("utf-8"), "iso-8859-1"); //解决中文乱码问题
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", downFileName);// aatachment  附件
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

    }

    /**
     * 获取 文件 流
     *
     * @param url
     * @return
     * @throws IOException
     */
    private byte[] getFile(String url) throws IOException {
        URL urlConet = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlConet.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(4 * 1000);
        InputStream inStream = con.getInputStream();    //通过输入流获取图片数据
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        byte[] data = outStream.toByteArray();
        return data;
    }

    /**
     * 读取 本地文件，转为字节数组
     * @param url 本地文件路径
     * @return
     * @throws IOException
     */
    private byte[] getImage(String url) throws IOException{
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(url));
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

        byte[] temp = new byte[2048];
        int size = 0;
        while ((size = in.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        in.close();
        byte[] content = out.toByteArray();
        return content;
    }



    @ControllerAspectIgnore
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public FileUploadResVo uploadFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam( name = "type", required = false) String type, @RequestParam("plmId") String plmId, @RequestParam( name = "version", required = false) Integer version) throws IOException {
        // 检查文件是否为空
        if (multipartFile.isEmpty()) {
            throw SyExceptionUtils.e("文件不能为空");
        }

        String fileFormat = "/home/storage/%s/%s/%s.%s";
        String yyyyMM = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String originalFilename = multipartFile.getOriginalFilename();

        type = "part-dxf";

        String path = String.format(fileFormat, type, yyyyMM, IdUtil.fastSimpleUUID(), originalFilename.substring(originalFilename.lastIndexOf(".") + 1));

        File dest = new File(path);
        FileUtils.copyToFile(multipartFile.getInputStream(), dest);

        FileUploadResVo resVo = new FileUploadResVo();
        resVo.setPath(path);
        resVo.setOriginalFilename(originalFilename);

        OrderPart orderPart = orderPartMapper.lambdaQuery().eq(OrderPart::getPlmId, plmId).eq(OrderPart::getMaterType, "Platepart").one();
        if (ObjectUtils.isEmpty(orderPart)) {
            throw SyExceptionUtils.e("未查询到零件：{}", plmId);
        }
        orderPart.setDxfUrl(path);
        orderPart.setVersionCode(orderPart.getVersionCode() + 1);
        orderPart.setDrawStatus(2);
        orderPart.setDrawUpdateTime(LocalDateTime.now());
        orderPartMapper.updateById(orderPart);

        return resVo;

    }

}
